package com.gzqylc.docker.extend.auth.inspector;

import com.google.common.collect.Lists;
import com.gzqylc.framework.security.LoginSession;
import com.gzqylc.lang.tool.MD5Tool;
import com.gzqylc.lang.web.jwt.JwtPayload;
import com.gzqylc.lang.web.jwt.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Desc：TODO
 * @ClassName LoginSessionInterceptor
 * @Author 孔晓文
 * @Date 2022/2/21 下午6:03
 */
@Component
@Slf4j
public class CustomLoginSessionInterceptor implements HandlerInterceptor {


    public static final List<String> NOT_FILTER_URLS = Lists.newArrayList("public","login","/api/host/notifyAdd","agent","log","logs","runner_hook");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断url是否拦截
        String url = request.getRequestURI();

        for (String notFilterUrl : NOT_FILTER_URLS) {
            if (url.contains(notFilterUrl)){
                return true;
            }
        }
        String jwt = JwtTool.getJwt(request);
        //判断是否合法
        JwtPayload payload = null;
        try {
            payload = JwtTool.getValidPayload(jwt);
        }catch (Exception e) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        //合法判断是否被主动下线了
        LoginSession loginSession = LoginSession.get(jwt);
        if (loginSession == null || loginSession.getUserId() == null){
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
